import { Component, OnInit, EventEmitter, Output, ElementRef } from '@angular/core';

import { InitService } from 'app/public/serve/init/init.service';
import { HintsService } from 'app/public/serve/hints/hints.service';
import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';

import { app } from '../application.data';
import { appUrl } from '../application.url';

declare var $: any;

@Component({
  selector: 'application-edit',
  templateUrl: './application-edit.component.html',
  styleUrls: ['./application-edit.component.css']
})
export class ApplicationEditComponent implements OnInit {
 
  @Output() onSubmit = new EventEmitter<void>();

  app: any = app;

  details     : object;
  authType    : Array<any> = [];         // 许可类型
  scopes      : Array<any> = [];         // 授权范围

  submitAuthType : Array<string> = [];   // 许可类型
  submitScopes   : Array<string> = [];   // 授权范围

  hasCheckbox : boolean = false;         // 复选框是否勾选

  constructor(
    public initService: InitService,
    private request: CudTableService,
    private hintsService: HintsService
  ) { }

  ngOnInit() {
  }

  /**
   * 详情（修改）
   * @param appId 
   */ 
  _details(appId) {

    this._empty();

  	let grantType : Array<string> = [];
  	let scope     : Array<string> = [];

    this.request
        .postRequest(`${ appUrl.getAppsInfo }${ appId }`, '')
  		  .then((data:any)=>{

          this.details = data;

          // 许可类型
          this.submitAuthType = grantType = data.result.grantType.split(',');

            for(let i=0; i<data.authType.length; i++) {

	          	this.authType.push(
	          		{ 
	          		  'displayName'	: data.authType[i].displayName, 
	          		  'sysValue'	  : data.authType[i].sysValue, 
	          		  'isSelect'	  : ''
	          		}); 
		          	for(let j=0; j<grantType.length; j++) { 
		          		if(data.authType[i].sysValue == grantType[j]) {
		          			this.authType[i].isSelect = true;
		          		}
		          	}
            }

          // 授权范围
          this.submitScopes = scope = data.result.scope.split(',');

            for(let i=0; i<data.scopes.length; i++) {
          		this.scopes.push(
          		{
          			'serviceTypeName' : data.scopes[i].serviceTypeName,
          			'scopesTypeVo'	  : []
          		});

	          	for(let j=0; j<data.scopes[i].scopesTypeVo.length; j++) {
	          		this.scopes[i].scopesTypeVo.push(
	          		{
	          			'scopeName'	 : data.scopes[i].scopesTypeVo[j].scopeName,
	          			'scopesCode' : data.scopes[i].scopesTypeVo[j].scopesCode,
	          			'isSelect'	: ''
	          		});

	          		for(let k=0; k<scope.length; k++) {
	          			if(data.scopes[i].scopesTypeVo[j].scopesCode == scope[k]) {
	          				this.scopes[i].scopesTypeVo[j].isSelect=true;
	          			}
	          		}
	          	}
            }

  		})
  		.catch(err=> {
        console.log('请检查您的网络！');
        return
      });

  }

  /**
   * 许可类型
   * @param val 
   * @param bool 
   */ 
  _grantType(val, bool) {
  	if(bool) {
  		this.submitAuthType.push(val);
  	}
  	else {
  		this._remove(this.submitAuthType, val);
  	}

  	this._check(this.submitAuthType.length, this.submitScopes.length);
  }

  /**
   * 授权范围
   * @param val 
   * @param bool 
   */ 
  _scope(val, bool) {
  	if(bool) {
  		this.submitScopes.push(val);
  	}
  	else {
  		this._remove(this.submitScopes, val);
  	}
  	this._check(this.submitAuthType.length, this.submitScopes.length);
  }

  /**
   * 反选
   * @param arr 
   * @param val 
   */ 
  private _remove(arr, val) {
    for(let i in arr) {
      if(arr[i]==val) {
        arr.splice(i,1);
      }
    }
  }

  /**
   * 校验是否勾选复选框
   * @param len1 
   * @param len2 
   */ 
  private _check(len1, len2) {
    if(len1>0&&len2>0) {
      this.hasCheckbox = false;
    }
    else {
      this.hasCheckbox = true;
    }
  }

  /**
   * 清空数组
   */
  private _empty() {
    this.authType = [];
    this.scopes = [];
  }

  /************************ 修改 ************************/

  /**
   * 修改
   * @param info 
   */
  _onSubmit(info: any) {

      let getRes;
      let formData = new FormData();

      formData.append('parentId',      app.tree['parentId']);
      formData.append('institutionId', app.tree['institutionId']);
      formData.append('relationsId',   app.tree['relationsId']);

      for(let key in info) {
        formData.append(key, info[key]);
      }

      formData.append('target',     'sys/app/'+info.appKey.substr(-8));
      formData.append("grantType",  this.submitAuthType.toString()||'');
      formData.append("scope",      this.submitScopes.toString()||'');
      formData.append("imageinfo",  $('#picID2')[0].files[0]||'');

      $.ajax({
          url          : appUrl.modify,
          type         : 'POST',
          data         : formData,
          async        : false,
          cache        : true,
          contentType  : false,
          processData  : false,
          success: function (res) { 
              getRes = res;
          },
          error: function (err) {
              this.hintsService._operationHints('error', 'error');
          }
      });
      if (getRes.result_code == '0000') {
        this.onSubmit.emit();
      }
      this.hasCheckbox = false;
      this.hintsService._operationHints(getRes.message, getRes.result_code);
      this.initService._init();
      $('#edit').modal('hide');
      return
  }

}

